package com.whfc.common.third.tq;

import com.whfc.common.third.tq.entity.*;
import com.whfc.common.util.DateUtil;
import com.whfc.common.util.HttpUtil;
import com.whfc.common.util.JSONUtil;
import com.whfc.common.util.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * @Description: 图强-定位器-API
 * @author: xugcheng
 * @version: 1.0
 * @date: 2021-11-15 17:50
 * http://opendoc.aichezaixian.com/#/developerTQ
 */
public class TQApi {

    private static Logger logger = LoggerFactory.getLogger(TQApi.class);

    private static final String DEFAUT_URL = "http://open.aichezaixian.com/route/rest";

    private static final Integer SUCCESS = 0;

    /**
     * key
     */
    private String appKey;

    /**
     * secret
     */
    private String appSecret;

    /**
     * 用户名
     */
    private String username;

    /**
     * 密码
     */
    private String password;

    public TQApi(String appKey, String appSecret, String username, String password) {
        this.appKey = appKey;
        this.appSecret = appSecret;
        this.username = username;
        this.password = password;
    }

    /**
     * 获取accessToken
     *
     * @return
     */
    public AccessTokenData accessToken() {
        Map<String, String> params = new HashMap<>();
        params.put("app_key", appKey);
        params.put("v", "1.0");
        params.put("timestamp", DateUtil.formatDateTime(new Date()));
        params.put("sign_method", "md5");
        params.put("format", "json");
        params.put("method", "jimi.oauth.token.get");

        try {
            params.put("user_id", username);
            params.put("user_pwd_md5", MD5Util.md5Encode(password));
            params.put("expires_in", "7200");

            String sign = signTopRequest(params, appSecret, "md5");
            params.put("sign", sign);
        } catch (IOException ex) {
            logger.error("", ex);
        }

        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("Content-Type", "application/x-www-form-urlencoded");

        String response = HttpUtil.doPost(DEFAUT_URL, params, headerMap);
        AccessTokenResult ret = JSONUtil.parseObject(response, AccessTokenResult.class);
        if (ret != null && SUCCESS.equals(ret.getCode())) {
            return ret.getResult();
        }
        return null;
    }

    /**
     * 获取账号下所有设备定位信息
     *
     * @return
     */
    public List<LocationData> getLocations(String accessToken) {

        Map<String, String> params = new HashMap<>();
        params.put("app_key", appKey);
        params.put("v", "1.0");
        params.put("timestamp", DateUtil.formatDateTime(new Date()));
        params.put("sign_method", "md5");
        params.put("format", "json");
        params.put("method", "jimi.user.device.location.list");

        try {
            params.put("access_token", accessToken);
            params.put("target", username);
            params.put("map_type", "GOOGLE");

            String sign = signTopRequest(params, appSecret, "md5");
            params.put("sign", sign);
        } catch (IOException ex) {
            logger.error("", ex);
        }

        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("Content-Type", "application/x-www-form-urlencoded");

        String response = HttpUtil.doPost(DEFAUT_URL, params, headerMap);
        LocationResult result = JSONUtil.parseObject(response, LocationResult.class);
        logger.info("查询定位信息,code:[],msg:{}", result.getCode(), result.getMessage());
        return result.getResult();
    }

    /**
     * 获取指定设备的定位信息
     *
     * @param accessToken
     * @param imeis
     * @return
     */
    public List<LocationData> getLocations(String accessToken, List<String> imeis) {
        Map<String, String> params = new HashMap<>();
        params.put("app_key", appKey);
        params.put("v", "1.0");
        params.put("timestamp", DateUtil.formatDateTime(new Date()));
        params.put("sign_method", "md5");
        params.put("format", "json");
        params.put("method", "jimi.device.location.get");

        try {
            params.put("access_token", accessToken);
            params.put("imeis", StringUtils.join(imeis, ","));
            params.put("map_type", "GOOGLE");

            String sign = signTopRequest(params, appSecret, "md5");
            params.put("sign", sign);
        } catch (IOException ex) {
            logger.error("", ex);
        }

        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("Content-Type", "application/x-www-form-urlencoded");

        String response = HttpUtil.doPost(DEFAUT_URL, params, headerMap);
        LocationResult result = JSONUtil.parseObject(response, LocationResult.class);
        logger.info("查询定位信息,code:[],msg:{}", result.getCode(), result.getMessage());
        return result.getResult();
    }

    /**
     * 获取账号下所有设备IMEI
     *
     * @param accessToken
     * @return
     */
    public List<ImeiData> getImeis(String accessToken) {
        Map<String, String> params = new HashMap<>();
        params.put("app_key", appKey);
        params.put("v", "1.0");
        params.put("timestamp", DateUtil.formatDateTime(new Date()));
        params.put("sign_method", "md5");
        params.put("format", "json");
        params.put("method", "jimi.user.device.list");

        try {
            params.put("access_token", accessToken);
            params.put("target", username);
            params.put("map_type", "GOOGLE");

            String sign = signTopRequest(params, appSecret, "md5");
            params.put("sign", sign);
        } catch (IOException ex) {
            logger.error("", ex);
        }

        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("Content-Type", "application/x-www-form-urlencoded");

        String response = HttpUtil.doPost(DEFAUT_URL, params, headerMap);
        ImeiResult result = JSONUtil.parseObject(response, ImeiResult.class);
        return result.getResult();
    }

    /**
     * 参数签名
     *
     * @param params
     * @param secret
     * @param signMethod
     * @return
     * @throws IOException
     */
    public static String signTopRequest(Map<String, String> params, String secret, String signMethod) throws IOException {
        // 第一步：检查参数是否已经排序
        String[] keys = params.keySet().toArray(new String[0]);
        Arrays.sort(keys);

        // 第二步：把所有参数名和参数值串在一起
        StringBuilder query = new StringBuilder();
        if ("md5".equals(signMethod)) {
            query.append(secret);
        }
        for (String key : keys) {
            String value = params.get(key);
            if (StringUtils.isNotEmpty(key) && StringUtils.isNotEmpty(value)) {
                query.append(key).append(value);
            }
        }

        // 第三步：使用MD5/HMAC加密
        byte[] bytes;
        if ("hmac".equals(signMethod)) {
            bytes = encryptHMAC(query.toString(), secret);
        } else {
            query.append(secret);
            bytes = encryptMD5(query.toString());
        }

        // 第四步：把二进制转化为大写的十六进制
        return byte2hex(bytes);
    }

    public static byte[] encryptHMAC(String data, String secret) throws IOException {
        byte[] bytes = null;
        try {
            SecretKey secretKey = new SecretKeySpec(secret.getBytes("UTF-8"), "HmacMD5");
            Mac mac = Mac.getInstance(secretKey.getAlgorithm());
            mac.init(secretKey);
            bytes = mac.doFinal(data.getBytes("UTF-8"));
        } catch (GeneralSecurityException gse) {
            throw new IOException(gse.toString());
        }
        return bytes;
    }

    public static byte[] encryptMD5(String data) throws IOException {
        return encryptMD5(data.getBytes("UTF-8"));
    }

    private static byte[] encryptMD5(byte[] bytes) throws IOException {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new IOException(e.toString());
        }
        return md.digest(bytes);
    }

    public static String byte2hex(byte[] bytes) {
        StringBuilder sign = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if (hex.length() == 1) {
                sign.append("0");
            }
            sign.append(hex.toUpperCase());
        }
        return sign.toString();
    }
}
